package cn.signalpha.common.wechat.handler;

import cn.signalpha.modules.base.service.WxReplyRuleService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@AllArgsConstructor
public class MsgHandler extends AbstractHandler {

	private final WxReplyRuleService wxReplyRuleService;

	private static final String TRANSFER_CUSTOMER_SERVICE_KEY = "人工";

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

		String fromUser = wxMessage.getFromUser();
		String textContent = wxMessage.getContent();
		boolean autoReply = wxReplyRuleService.tryAutoReply(fromUser, textContent);

		//当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
		if (TRANSFER_CUSTOMER_SERVICE_KEY.equals(textContent) || !autoReply) {
			return WxMpXmlOutMessage
				.TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
				.toUser(fromUser).build();
		}
        //TODO 组装回复消息
		return null;
    }

}
